<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Requests\Api\MiniProgramRiddleRequest;
// # 模型
use App\Models\MiniprogramUser; // 小程序用户
use App\Models\Riddle; // 谜语

class MiniProgramRiddlesController extends Controller {
    public function userInfo(MiniProgramRiddleRequest $request) { // 获取用户信息
        $openid = $request->openid;
        $userinfo = MiniprogramUser::where('openid', $openid)->first();

        if ( $userinfo ) {
            return $this->response->array([
                'result' => true,
                'name' => $userinfo->name,
                'phone' => $userinfo->phone,
                'count' => $userinfo->count, // 答题数量
                'reward' => 'baidu', // 奖品
            ])->setStatusCode(201);
        } else {
            return $this->response->array([
                'result' => false,
                'message' => '没有数据',
            ])->setStatusCode(201);
        }
    }
    public function saveUserInfo(MiniProgramRiddleRequest $request) { // 存储用户信息
        $data = $request->all();
        $userinfo = MiniprogramUser::where('openid', $data['openid'])->first();

        if ( $userinfo ) {
            if ( isset($data['name']) ) $userinfo->name = $data['name'];
            if ( isset($data['phone']) ) $userinfo->phone = $data['phone'];
            if ( isset($data['count']) ) $userinfo->count = $data['count'];

            $result = $userinfo->save();
        } else {
            $result = MiniprogramUser::create($data);
        }

        return $this->response->array([
            'result' => true,
        ])->setStatusCode(201);
    }
    public function questionBank(MiniProgramRiddleRequest $request) { // 题库
        // $category = $request->category;
        $questions = Riddle::orderBy(\DB::raw('RAND()'))
            ->take(10)
            ->get()
            ->toArray();

        if ( $questions ) {
            return $this->response->array([
                'result' => true,
                'data' => $questions,
            ])->setStatusCode(201);
        } else {
            return $this->response->array([
                'result' => false,
                'code' => 1,
                'message' => '没有数据',
            ])->setStatusCode(201);
        }
    }
}
